<template>
	<div class="cache-config">
		<a-form-item label="缓存设置">
			<a-space direction="vertical" style="width: 100%">
				<a-checkbox v-model:checked="enableCache" @change="handleCacheChange"> 启用缓存 </a-checkbox>

				<a-form-item v-if="enableCache" label="缓存超时时间" style="margin-bottom: 0">
					<a-input-number
						v-model:value="cacheTimeout"
						:max="3600"
						:min="60"
						:step="60"
						addon-after="秒"
						placeholder="300"
						@change="handleCacheChange"
					/>
					<div class="form-help-text">API发现结果的缓存时间，默认5分钟</div>
				</a-form-item>
			</a-space>
		</a-form-item>
	</div>
</template>

<script setup>
	import { ref, watch } from 'vue'

	// Props
	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({})
		}
	})

	// Emits
	const emit = defineEmits(['update:modelValue', 'change'])

	// 缓存配置
	const enableCache = ref(true)
	const cacheTimeout = ref(300)

	// 监听props变化
	watch(
		() => props.modelValue,
		(newVal) => {
			if (newVal) {
				enableCache.value = newVal.enableCache === 'true'
				cacheTimeout.value = parseInt(newVal.cacheTimeout || '300')
			}
		},
		{ deep: true, immediate: true }
	)

	// 更新配置
	const updateConfig = () => {
		const config = {
			enableCache: enableCache.value.toString(),
			cacheTimeout: cacheTimeout.value.toString()
		}

		emit('update:modelValue', config)
		emit('change', config)
	}

	// 处理缓存配置变化
	const handleCacheChange = () => {
		updateConfig()
	}

	// 获取缓存配置
	const getCacheConfig = () => {
		return {
			enableCache: enableCache.value.toString(),
			cacheTimeout: cacheTimeout.value.toString()
		}
	}

	// 验证配置
	const validateConfig = () => {
		if (enableCache.value && (cacheTimeout.value < 60 || cacheTimeout.value > 3600)) {
			return { valid: false, message: '缓存超时时间应在1分钟到1小时之间' }
		}

		return { valid: true }
	}

	// 暴露方法给父组件
	defineExpose({
		getCacheConfig,
		validateConfig
	})
</script>

<style scoped>
	.cache-config {
		padding: 0;
	}

	.form-help-text {
		font-size: 12px;
		color: #999;
		margin-top: 4px;
	}
</style>
